package com.mall.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    //引入工厂
    private static SqlSessionFactory factory;

    //静态代码块，先行执行的代码
    static {
        //1、加载资源
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //2、创建一个构建者
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //3、用构建者构建工厂
        factory = builder.build(resourceAsStream);

    }

    public static SqlSession openSession(){
        return factory.openSession();

    }
}
